'use strict';

const Controller = require('egg').Controller;
const utils = require('utility');

class HomeController extends Controller {

  async admincreat() {
    const { ctx } = this;
    const { admin, adpasd, role } = ctx.request.body;
    if (!(admin && adpasd && role)) {
      return ctx.body = { success: false, msg: '请传入指定参数' };
    }
    try {

      const ifadmin = await ctx.model.Administrators.findAll({
        where: {
          admin,
        },
      });
      if (ifadmin[0]) {
        return ctx.body = { success: false, msg: '该管理员已经存在' };
      }

      await ctx.model.Administrators.create({
        admin,
        adpasd: utils.md5(adpasd),
        role,
        addTime: Date.now(),
        uportrait: 'https://icweiliimg6.pstatp.com/weili/sm/254329013950218271.jpg',
      });
      ctx.body = { success: true, msg: '添加成功' };
    } catch (e) {
      ctx.body = { success: false, msg: '发送为止错误' };
    }
  }

  async adminfind() {
    const { ctx } = this;
    const { role } = ctx.request.body;
    const where = {};
    if (role) {
      where.role = role;
    }
    try {
      const res = await ctx.model.Administrators.findAll({
        where,
        attributes: {
          exclude: [ 'adpasd' ],
        },
        order: [[ 'role' ]],
      });
      ctx.body = { success: true, data: res };
    } catch (e) {
      ctx.body = { success: false, msg: '发生未知错误' };
    }
  }

  async admindestory() {
    const { ctx } = this;
    const { adminid } = ctx.request.body;
    if (!adminid) return ctx.body = { success: false, msg: '请传入指定参数' };
    try {
      await ctx.model.Administrators.destroy({
        where: {
          adminid,
        },
      });
      ctx.body = { success: true, msg: '删除成功' };
    } catch (e) {
      ctx.body = { success: false, msg: '发生未知错误' };
    }
  }

  async adminlogin() {
    const { ctx } = this;
    const { admin, adpasd } = ctx.request.body;
    if (!(admin && adpasd)) {
      return ctx.body = { success: false, msg: '请传入指定参数' };
    }
    try {
      const res = await ctx.model.Administrators.findOne({
        where: {
          admin,
        },
      });
      if (!res) return ctx.body = { success: false, msg: '没有该管理员' };
      const newadpasd = utils.md5(adpasd);
      if (res.adpasd != newadpasd) return ctx.body = { success: false, msg: '用户密码不匹配' };
      res.adpasd = '******';
      ctx.body = { success: true, msg: '登录成功', data: res };
    } catch (e) {
      ctx.body = { success: false, msg: '发生未知错误' };
    }
  }


}

module.exports = HomeController;
